﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class MessageDetail : BaseUserControl
    {
        public String MessageType { get; set; }
        //MessageType:
            //post
            //quote
            //annonce
            //news
            //privatemessage
            //mail

        private Int32 _forumTopicId;
        public Int32 ForumCategoryId { get; set; }
        public Int32 ForumTopicId
        {
            get { return this._forumTopicId; }
            set
            {
                this._forumTopicId = value;
                var ThisTopic = ForumTopicDal.GetEntity(value);
                if (ThisTopic == null)
                    throw new HttpException(404, String.Format("This Topic has been deleted: {0}", _forumTopicId));

                var ThisTopicLabel = ThisTopic.LabelForumTopic;
                ThisMaster.Page.Title = prefixTitle + ThisTopicLabel;
            }
        }
        public Int32 MessageId { get; set; }

        public String UserAddressIp { get; set; }
        private Int32 UserRightLevel { get; set; }
        private Boolean IsTopicUnlocked;
        private String SaidLocalized = "Said".ToLocalizedString();

        /// <summary>
        /// Route : {culture}/{targetPage}/{messagetype}/{messageid} ,  "targetPage", "messagedetail"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.RouteData.Values["messagetype"] != null)
                this.MessageType = Page.RouteData.Values["messagetype"].ToString().ToLower();

            if (Page.RouteData.Values["topicid"] != null)
                this.ForumTopicId = Int32.Parse(Page.RouteData.Values["topicid"].ToString());

            if (Page.RouteData.Values["messageid"] != null)
                this.MessageId = Int32.Parse(Page.RouteData.Values["messageid"].ToString());

            if (MessageType == "post" || MessageType == "quote")
            {
                if (ForumTopicDal.GetEntity(this.ForumTopicId) == null)
                    throw new HttpException(404, "This topic don't exists.");

                this.ForumCategoryId = ForumCategoryDal.GetCategoryIdByTopicId(this.ForumTopicId);

                //Si le sujet est vérouillé alors retour à l'affichage du sujet
                IsTopicUnlocked = ForumTopicDal.GetEntity(this.ForumTopicId).IsUnlocked;
                if (!IsTopicUnlocked)
                    ReturnUrlButton_Click(null, null);

                //Vérifier si l'utilisateur à accès à ce message
                this.UserRightLevel = UserAccessDal.UserRightLevel(this.ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
                if (this.UserRightLevel < RightLevel.Author)
                    Response.Redirect(String.Format("~/{0}/connexion/?returnurl=~{1}", ThisMaster.Requester.Culture, Request.RawUrl));

                if (MessageType == "quote")
                {
                    var ForumPostEditing = ForumPostDal.GetEntity(this.MessageId);
                    ForumPostEditor.Content = "<fieldset style=\"display: block;text-align: left;\"><legend>" +
                        ForumPostEditing.PostMessage.Author +
                        " " + (SaidLocalized) + " : </legend><p>" +
                        ForumPostEditing.PostMessage.Message +
                        "</p></fieldset><br /><br />";
                }
                else
                    //Charger les controles s'il s'agit d'un post à éditer
                    if (this.MessageId > 0)
                    {
                        ForumPost updatingPost = ForumPostDal.GetEntity(this.MessageId);
                        ForumPostIdLabel.Text = updatingPost.Id.ToString();
                        LabelForumMessageTextBox.Text = updatingPost.PostMessage.Label;
                        ForumPostEditor.Content = updatingPost.PostMessage.Message;
                    }
                this.Page.SetFocus(AddPostButton.ClientID);
            }
            ShowSmiliesLiteral.Text = ForumPostDal.GetSmilies();
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            Boolean IsTopicUnlocked = ForumTopicDal.GetEntity(this.ForumTopicId).IsUnlocked;

            CreateForumPostPanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;
            CreateYouTubePanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;
            CreateImageLinkPanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;
        }
        protected void ReturnUrlButton_Click(object sender, EventArgs e)
        {
            String urlDestination = String.Empty;
            urlDestination = String.Format("~/{0}/forumpost/{1}/?topicpagenumber=1"
                        , ThisMaster.Requester.Culture
                        , this._forumTopicId);
            Response.Redirect(urlDestination);
        }
        protected void AddPostButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            if (ForumPostEditor.Content != string.Empty)
            {
                String urlDestination = String.Empty;
                Int32 newPostId;

                if (ForumPostIdLabel.Text == "0") // création d'un message
                {
                    newPostId = ForumPostDal.CreateEntity(new FranceTriple.Dal.ForumPost()
                    {
                        PostMessage = new MessageType()
                        {
                            Label = LabelForumMessageTextBox.Text,
                            Message = ForumPostEditor.Content,
                            Author = ThisMaster.Requester.Profile.UserName,
                            AuthorAdressIp = this.UserAddressIp
                        },
                        ForumTopic = ForumTopicDal.GetEntity(this.ForumTopicId)
                    });
                }
                else // Mise à jour d'un message
                {
                    newPostId = Int32.Parse(ForumPostIdLabel.Text);
                    ForumPost ForumPostUpdated = ForumPostDal.GetEntity(newPostId);
                    ForumPostUpdated.PostMessage = new MessageType()
                    {
                        Label = LabelForumMessageTextBox.Text,
                        Message = ForumPostEditor.Content,
                        Author = ThisMaster.Requester.Profile.UserName,
                        AuthorAdressIp = this.UserAddressIp
                    };

                    ForumPostDal.UpdateEntity(ForumPostUpdated);
                }

                ForumPostIdLabel.Text = "0";
                ForumPostEditor.Content = String.Empty;
                LabelForumMessageTextBox.Text = String.Empty;

                //Mise à jour du cache des 20 derniers sujets discutés, sur le portail.
                Cache.Remove("LastTopicsCacheKey");

                urlDestination = String.Format("~/{0}/forumpost/showpost/{1}", ThisMaster.Requester.Culture, newPostId.ToString());
                Response.Redirect(urlDestination);
            }
        }
        protected void AddImageLinkButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            StringBuilder sb = new StringBuilder();
            if (NavigateUrlTextBox.Text != String.Empty)
                sb.Append(String.Format("<a href=\"{0}\">", NavigateUrlTextBox.Text));

            sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\"  target=\"_blank\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text));

            if (NavigateUrlTextBox.Text != String.Empty)
                sb.Append("</a>");

            //Int32 width=0;
            //Int32 height=0;
            //sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\" width=\"{2}\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text, width.ToString()));
            //sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\" height=\"{2}\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text, height.ToString()));

            ForumPostEditor.Content = ForumPostEditor.Content + sb.ToString();

            NavigateUrlTextBox.Text = String.Empty;
            ImageUrlTextBox.Text = String.Empty;
            AlternateTextTextBox.Text = String.Empty;
            //WidthTextBox.Text = String.Empty;
            //HeightTextBox.Text = String.Empty;
        }

        protected void AddYouTubeButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            StringBuilder sb = new StringBuilder();
            if (TitleTextBox.Text != String.Empty)
                sb.Append(String.Format("<div class=\"colMain\"><fieldset class=\"Youtube\"><legend>{0}</legend><p class=\"centerP\">", TitleTextBox.Text));

            sb.Append(String.Format("<iframe width=\"580\" height=\"320\" src=\"{0}\" frameborder=\"0\" allowfullscreen></iframe></p></fieldset></div>", YouTubeUrlTextBox.Text));

            ForumPostEditor.Content = ForumPostEditor.Content + sb.ToString();

            YouTubeUrlTextBox.Text = String.Empty;
            TitleTextBox.Text = String.Empty;
        }
    }
}
